//聊天室controller

angular.module("chat.controller", ['myservice'])

.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider.state("chatRoom", {
        url: "/chatRoom/{username}",
        templateUrl: "templates/chatRoom/chatRoom.html"
    });

})

.controller("chatRoomController", function($ionicScrollDelegate,$ionicPopover, $ionicPosition, $timeout, $document, $ionicPopup, $scope, $stateParams, $state, socket) {

    var username = $stateParams.username;

    var self = this;

    console.log("@@come in room :" + username);

    $scope.data = {};

    $scope.data.messages = [];

    $scope.isShowCanvas = false;

    var context = null;

    var offx, offy;

    var canvasWidth, canvasHeight;


    socket.on('connect', function() {
        //Add user called nickname
        console.log("@@##connect !" + username);
        // socket.emit('login', {userid:"111",username:"zhai"});

        // socket.on("login",function(data){

        //     console.log("@@##login is %s", JSON.stringify(data));
        // });

        // socket.on('message', function(data) {
        //     console.log("@@##on messgae:" + JSON.stringify(data));

        //     $scope.data.messages.push(data);
        // });


    });

    socket.on('message', function(data) {
        console.log("@@##on messgae:" + JSON.stringify(data));

        if (data.showCanvas) {
            if (!$scope.isShowCanvas) {
                $scope.isShowCanvas = true;
                $scope.showCanvas();
            } else if ($scope.isShowCanvas) {


                var canvas = document.getElementById("mycanvas");
                canvas.width = window.innerWidth;

                var dom = $ionicPosition.offset([canvas]);

                offx = dom.left;
                offy = dom.top;

                canvasWidth = dom.width;
                canvasHeight = dom.height;
                console.log("@@##the canvas:" + JSON.stringify(dom));
            };
        } else {
            $scope.data.messages.push(data);
            $ionicScrollDelegate.scrollBottom();
        }


    });

    socket.on("come in room", function(username) {
        var mmsg = {
            username: "",
            message: "Welcome :" + username
        }
        $scope.data.messages.push(mmsg);
        $ionicScrollDelegate.scrollBottom();
    });

    socket.emit('come in room', username);

    socket.on("operation", function(data) {
        if (data.showCanvas) {
            $scope.isShowCanvas = true;
            self.showCanvas();
        };
    });

    socket.on("draw", function(data) {
        console.log("@@##draw data is " + JSON.stringify(data));
        //{type:"start",point:{x:"",y:""}} //type:"start","move","end"
        if (data.type && context) {
            console.log("@@##offx offy:" + offx + " " + offy);
            var x = data.x - offx;
            var y = data.y - offy;
            context.lineWidth = 5;
            context.strokeStyle = "red";
            context.stroke();
            if (data.type == "start") {


                console.log("@@##start line " + JSON.stringify(data));
                context.beginPath();
                context.moveTo(x, y);

            } else if (data.type == "move") {
                console.log("@@##move line " + JSON.stringify(data));
                context.lineTo(x, y);

            } else if (data.type == "end") {
                //context.closePath();

                // context.lineWidth = 10;
                // context.strokeStyle = "red";
                // context.stroke();
                console.log("@@s##end line ");
            } else if (data.type == "clear") {
                console.log("@@##the canvas:" + canvasWidth + " " + canvasHeight);
                //context.closePath();
                context.beginPath();
                context.clearRect(0, 0, canvasWidth, canvasHeight);
                x = 0;
                y = 0;

            }





        }


    });


    // socket.on('new message', function(data) {
    //     console.log("@@##on messgae:" + data);
    //     var msg = {};
    //     msg.message = data;
    //     msg.userName = "zhisdsdsd";
    //     $scope.data.messages.push(msg);
    // });

    $scope.showCanvas = function() {
        $scope.isShowCanvas = true;
        socket.emit("message", {
            showCanvas: true
        });


        var canvas = document.getElementById("mycanvas");


        context = canvas.getContext("2d");

        $scope.context = context;

        // context.strokeStyle = "red";
        // context.fillStyle = "blue";
        // context.fillRect(10, 10, 500, 500);
        canvas.addEventListener("touchstart", function(e) {
            var x, y;
            // 如果这个元素的位置内只有一个手指的话
            if (e.targetTouches.length == 1) {　　　　
                e.preventDefault(); // 阻止浏览器默认事件，重要 
                var touch = e.targetTouches[0];
                // 把元素放在手指所在的位置
                x = touch.pageX;
                y = touch.pageY;

                console.log("@@##touchstart screen:" + touch.screenX + " " + touch.screenY);
                console.log("@@##touchstart client:" + touch.clientX + " " + touch.clientY);
                console.log("@@##touchstart page:" + touch.pageX + " " + touch.pageY);
            }

            // console.log("@@##move !!"+e.pageX+" "+e.pageY);
            socket.emit("draw", {
                type: "start",
                x: parseInt(x),
                y: parseInt(y)
            });


        }, true);

        canvas.addEventListener("touchend", function(e) {
            var x, y;
            // 如果这个元素的位置内只有一个手指的话
            if (e.targetTouches.length == 1) {　　　　
                e.preventDefault(); // 阻止浏览器默认事件，重要 
                var touch = e.targetTouches[0];
                // 把元素放在手指所在的位置
                x = touch.pageX;
                y = touch.pageY;
            }

            // console.log("@@##move !!"+e.pageX+" "+e.pageY);
            socket.emit("draw", {
                type: "end",
                x: parseInt(x),
                y: parseInt(y)
            });


        }, true);


        canvas.addEventListener("touchmove", function(e) {
            var x, y;
            // 如果这个元素的位置内只有一个手指的话
            if (e.targetTouches.length == 1) {　　　　
                e.preventDefault(); // 阻止浏览器默认事件，重要 
                var touch = e.targetTouches[0];
                // 把元素放在手指所在的位置
                x = touch.pageX;
                y = touch.pageY;
            }

            // console.log("@@##move !!"+e.pageX+" "+e.pageY);
            socket.emit("draw", {
                type: "move",
                x: parseInt(x),
                y: parseInt(y)
            });


        }, true);
    }


    $scope.send = function() {
        console.log("@@##clearCanvas");
        var msg = $scope.message.message;

        var createTime = new Date();
        var mmsg = {
            sendTime: createTime.toLocaleString(),
            username: username,
            message: msg
        }
        socket.emit("message", mmsg);
        $scope.message.message = null;
    };

    $scope.clear = function() {
        console.log("@@##clearCanvas");
        if (context) {
            //清空画布
            socket.emit("draw", {
                type: "clear"
            });
        }
    }



})
